// pages/order/index.js
Page({
  data: {
    Obj:{},
    currentTab: 0, // 当前选中的标签页
    tabs: [
      { name: '厨房订单'},
      { name: '我的下单'},
    ],
    orderList: [], // 订单列表数据
    loading: false,  // 加载状态
    noMore: false,   // 是否无更多数据
    lastDoc: null,    // 最后一条文档（用于分页）
    app:null,
    db:null,
    userInfo:{},
    isLoggedIn:false,

    // 下拉刷新相关
    refreshHeight: 80, // 刷新区域高度
    refreshTranslate: -80, // 刷新区域位移
    refreshStatus: 'pulling', // pulling, ready, loading
    startY: 0,
    currentY: 0,
    isRefreshing: false
  },

  onLoad() {
    const app = getApp();
    this.setData({
      app:app
    })
    console.log(app.globalData.env); // 输出: your-env-id
    // 获取默认环境的数据库引用
    this.setData({
      db:app.globalData.db
    })
    const userInfo = wx.getStorageSync('userInfo');
    console.log('business userInfo',userInfo)
    this.setData({
      isLoggedIn: !!userInfo,
      userInfo: userInfo || {},
      Obj:{},

      tabs: [
        { name: '厨房订单'},
        { name: '我的下单'},
      ],
      orderList: [], // 订单列表数据
      loading: false,  // 加载状态
      noMore: false,   // 是否无更多数据
      lastDoc: null,    // 最后一条文档（用于分页）
    });

    // if(app.globalData.currentTab){
    //   this.setData({
    //     currentTab: Number(app.globalData.currentTab)
    //   })
    //   delete app.globalData.currentTab
    // }
    this.loadOrderList(true);
  },

  // 加载订单列表
  loadOrderList(init = false) {
    console.log('this.data.loading',this.data.loading,this.data.noMore)
    if (this.data.loading || this.data.noMore) return
    
    this.setData({ loading: true })
    wx.showLoading({ title: '加载中...' })
    if(this.data.currentTab === 0){
      this.setData({
        Obj:{
          cheferId:this.data.userInfo._openid
        }
      })
    }else if(this.data.currentTab === 1){
      this.setData({
        Obj:{
          customerId:this.data.userInfo._openid
        }
      })
    }
    this.data.db.collection('goodsList').where(this.data.Obj)
    .orderBy('createTime','desc')
    .skip(init ? 0 : this.data.orderList.length) // 跳过已加载数据
    .limit(20) // 每次20条
    .get()
    .then(res => {
      if(res && res.data && res.data.length > 0){
        console.log('res',res.data,this.data.Obj,this.data.currentTab)
        this.setData({
          orderList: init ? res.data.map(item => ({
            ...item,
            formattedTime: this.getFormats(item.createTime),
            allCount:item.goodsList.reduce((total, item) => total + Number(item.num), 0),
            allPrice:item.goodsList.reduce((total, item) => total + Number(item.price), 0)
          })) : [...this.data.orderList, ...res.data.map(item => ({
            ...item,
            formattedTime: this.getFormats(item.createTime)
          }))], 
          noMore: res.data.length < 20,
          lastDoc: res.data[res.data.length - 1], // 记录最后一条
        })
      }
    })
    .catch (err =>  {
      wx.showToast({ title: '加载失败', icon: 'none' })
    })
    .finally(() => {
      this.setData({ loading: false })
      wx.hideLoading()

      if(this.data.isRefreshing){
        this.resetRefresh()
        this.setData({ isRefreshing: false })
      }

    }) 
  },
   // 滚动到底部触发
  onReachBottom() {
    this.loadOrderList()
  },
  getFormats(timestamp) {
    const date = new Date(timestamp);
  
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
  
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  },

  // 切换标签页
  switchTab(e) {
    const index = e.currentTarget.dataset.index;
    if (this.data.currentTab === index) return;
    
    this.setData({
      currentTab: index,
      noMore: false,
      lastDoc:null,
      orderList:[],
      // 下拉刷新相关
      refreshHeight: 80, // 刷新区域高度
      refreshTranslate: -80, // 刷新区域位移
      refreshStatus: 'pulling', // pulling, ready, loading
      startY: 0,
      currentY: 0,
      isRefreshing: false
    }, () => {
      this.loadOrderList(true);
    });
  },

  // 查看订单详情
  viewOrderDetail(e) {
    const orderId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/orderDetail/index?id=${orderId}&currentTab=${this.data.currentTab}`,
    })
  },

  // 取消订单
  cancelOrder(e) {
    const orderId = e.currentTarget.dataset.id;
    wx.showModal({
      title: '提示',
      content: '确定要取消此订单吗？',
      success: (res) => {
        if (res.confirm) {
          wx.showLoading({ title: '处理中...' });
          this.data.db.collection('goodsList').doc(orderId).update({
            data: {
              status:'已取消'
            },
            success: res => {
              wx.hideLoading();
              this.updateOrderStatus(orderId, '已取消');
              wx.showToast({ title: '取消成功', icon: 'success' });
            },
            fail: err => {
              wx.hideLoading()
              wx.showToast({
                title: '取消失败',
                icon: 'none'
              })
            }
          })
        }
      }
    });
  },
  delete(e){
    const orderId = e.currentTarget.dataset.id;
    wx.showModal({
      title: '提示',
      content: '确定要删除此订单吗？',
      success: (res) => {
        if (res.confirm) {
          wx.showLoading({
            title: `删除中...`,
          })
          this.data.db.collection('goodsList').doc(orderId).remove({
            success: res => {
              wx.hideLoading();
              this.updateOrderStatus(orderId, '已删除');
              wx.showToast({ title: '删除成功', icon: 'success' });
            },
            fail: err => {
              wx.hideLoading()
              wx.showToast({
                title: '删除失败',
                icon: 'none'
              })
            }
          })
        }
      }
    })
  },

  // 确认收货
  confirmReceipt(e) {
    const orderId = e.currentTarget.dataset.id;
    wx.showLoading({ title: '处理中...' });
    this.data.db.collection('goodsList').doc(orderId).update({
      data: {
        status:'已完成'
      },
      success: res => {
        wx.hideLoading();
        this.updateOrderStatus(orderId, '已完成');
        wx.showToast({ title: '操作成功', icon: 'success' });
      },
      fail: err => {
        wx.hideLoading()
        wx.showToast({
          title: '操作失败',
          icon: 'none'
        })
      }
    })
  },

  // 查看物流
  viewLogistics(e) {
    const orderId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/order/logistics?id=${orderId}`
    });
  },

  // 更新订单状态
  updateOrderStatus(orderId, newStatus) {
    if(newStatus === '已删除'){
      this.setData({
        orderList: this.data.orderList.filter(order => {
          return order._id !== orderId
        })
      });
    }else{
      this.setData({
        orderList: this.data.orderList.map(order => {
          if (order._id === orderId) {
            return { ...order, status: newStatus };
          }
          return order;
        })
      });
    }
  },
  onShow(){

  },
   // 触摸开始
   onTouchStart(e) {
     console.log('onTouchStart e',e,this.data.isRefreshing)
    if (this.data.isRefreshing) return
    
    this.setData({
      startY: e.touches[0].clientY,
      currentY: e.touches[0].clientY
    })
  },

  // 触摸移动
  onTouchMove(e) {
    console.log('onTouchMove e',e,this.data.isRefreshing)
    if (this.data.isRefreshing) return
    
    const currentY = e.touches[0].clientY
    const deltaY = currentY - this.data.startY
    const scrollTop = this.getScrollTop()

    console.log('onTouchMove scrollTop',scrollTop,currentY,deltaY)

    // 只有在顶部且下拉时才触发
    if (scrollTop <= 0 && deltaY > 0) {
      const translateY = Math.min(deltaY * 0.5, this.data.refreshHeight)
      
      this.setData({
        currentY: currentY,
        refreshTranslate: translateY - this.data.refreshHeight,
        refreshStatus: translateY >= this.data.refreshHeight ? 'ready' : 'pulling'
      })

      // 阻止默认滚动
      if (deltaY > 0) {
        return false
      }
    }
  },

  // 触摸结束
  onTouchEnd() {
    console.log('onTouchEnd e',this.data.isRefreshing,this.data.refreshStatus)
    if (this.data.isRefreshing) return

    if (this.data.refreshStatus === 'ready') {
      // 开始刷新
      this.startRefresh()
    } else {
      // 恢复原位
      this.resetRefresh()
    }
  },

  // 开始刷新
  startRefresh() {
    this.setData({
      refreshStatus: 'loading',
      refreshTranslate: 0,
      isRefreshing: true,
      noMore: false,
      lastDoc:null,
    })
    this.loadOrderList(true);
  },

  // 重置刷新状态
  resetRefresh() {
    this.setData({
      refreshTranslate: -this.data.refreshHeight,
      refreshStatus: 'pulling'
    })
  },
  onScroll(){

  },
  // 获取滚动位置
  getScrollTop() {
    let scrop = 0;
      const query = this.createSelectorQuery()
      query.select('.order-list').scrollOffset()
      query.exec((res) => {
        console.log('getScrollTop res',res[0].scrollTop)
        // resolve(res[0] ? res[0].scrollTop : 0)
        scrop = res[0].scrollTop
      })
      return scrop
  },
  getFormats(timestamp) {
    const date = new Date(timestamp);
  
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
  
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  },
});